package com.bardsoftware.foronuvolo.server;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DatastoreDiscussionChunk;
import com.bardsoftware.foronuvolo.data.DiscussionChunk;
import com.bardsoftware.foronuvolo.data.FeedItem;
import com.bardsoftware.foronuvolo.data.ForumUser;
import com.bardsoftware.foronuvolo.data.Message;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.google.appengine.repackaged.com.google.common.collect.Maps;

public class FeedHotServlet extends HttpServlet {
    private final DiscussionsViewPage myPageFormatter = new DiscussionsViewPage();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        if (!req.getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
            return;
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(JspHelper.getJspName("feed_hot.jsp"));

        Calendar c = Calendar.getInstance();
        c.add(Calendar.WEEK_OF_YEAR, -1);

        DiscussionChunk page = DatastoreDiscussionChunk.getHotPage();
        List<FeedItem> entries = Lists.newArrayListWithExpectedSize(page.getDiscussions().size());
        Date lastDate = null;
        for (Discussion d: page.getDiscussions()) {
            Date discussionUpdate = myPageFormatter.addUpdatedMessagesSince(entries, d, c.getTime());
            if (lastDate == null || lastDate.before(discussionUpdate)) {
                lastDate = discussionUpdate;
            }
        }
        if (lastDate == null) {
            lastDate = c.getTime();
        }
        Collections.sort(entries, new Comparator<FeedItem>() {
            public int compare(FeedItem o1, FeedItem o2) {
                return -o1.getUpdated().compareTo(o2.getUpdated());
            }
        });
        req.setAttribute("feed-updated", FeedItem.DATE_FORMAT.format(lastDate));
        req.setAttribute("entries", entries);
        dispatcher.forward(req, resp);
    }

}
